using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Musicman.Business;
using System.Text.RegularExpressions;
using System.IO;
using System.Net.Mail;
using Musicman.Utilities;
using System.Collections.Generic;

namespace MusicmanWeb
{
    public partial class Register : MusicmanPage
    {
        protected override void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                registerform.Visible = true;
            }

            if (Request["ACTIVATIONCODE"] == null && IsPostBack)
            {
                bool valid = true;
                int errCnt = 0;
                string validatioinErrors = "";

                valid = !UserManager.Instance.CheckMail(EmailaddressTxt.Text);
                if (!valid)
                {
                    errCnt++;
                    validatioinErrors += String.Format("{0}. User with that email address already registerred for Musicman <br/>", errCnt);
                }
                valid = Regex.IsMatch(EmailaddressTxt.Text, Musicman.Common.Constants.EmailRegex);
                if (!valid)
                {
                    errCnt++;
                    validatioinErrors += String.Format("{0}. Incorrect mail format <br/>", errCnt);
                }
                valid = !String.IsNullOrEmpty(NewPasswordTxt.Text);
                if (!valid)
                {
                    errCnt++;
                    validatioinErrors += String.Format("{0}. Password can't be empty <br/>", errCnt);
                }
                valid = NewPasswordTxt.Text == NewPassword2Txt.Text;
                if (!valid)
                {
                    errCnt++;
                    validatioinErrors += String.Format("{0}. New paswword and old password mismatch <br/>", errCnt);
                }
                valid = errCnt == 0;
                if (!valid)
                {
                    this.ValidationMessage.Text = validatioinErrors;
                    return;
                }

                Musicman.Common.Entities.User user = new Musicman.Common.Entities.User();
                user.Emailaddress = EmailaddressTxt.Text;
                user.Firstname = FirstnameTxt.Text;
                user.Lastname = LastNameTxt.Text;
                user.Password = NewPasswordTxt.Text;
                user.PersonSex = PersonSex.Text == "M" ? Musicman.Common.Entities.Sex.Male : Musicman.Common.Entities.Sex.Female;
                user.MailRequest = MailRequestCB.Checked;
                user.ActivationCode = Guid.NewGuid();
                
                if(! UserManager.Instance.AddNewUser(user))
                {
                    ValidationMessage.Text = "Error registerring user please try later";
                    return;
                }
                SendActivationMail(user);
                SetNotificationAdmins(user);
                ValidationMessage.Text = "User successfully registred. Check you email for activation!";
                registerform.Visible = false;
            }
            else if (Request["ACTIVATIONCODE"] != null)
            {
                registerform.Visible = false;
                string activationCode = Request["ACTIVATIONCODE"];
                if (UserManager.Instance.ActivateUser(activationCode)) // activate user
                {
                    this.ValidationMessage.Text = "User sucessfully registered";
                }
                else
                {
                    this.ValidationMessage.Text = "Error activating user try again later";
                }
            }
        }

        private void SendActivationMail(Musicman.Common.Entities.User user)
        {
            MailMessage email = new MailMessage();
            string mailTemplate = "";
            using (StreamReader sr = new StreamReader(File.Open(Server.MapPath("templates//activation_mail.html"), FileMode.Open, FileAccess.Read)))
            {
                mailTemplate = sr.ReadToEnd();
            }
            email.From = new MailAddress("musicmanservices@musicman.com", "Musicman");
            email.To.Add(new MailAddress(user.Emailaddress));
            email.Subject = String.Format("{0} {1}, welcome to Musicman", user.Firstname, user.Lastname);

            email.Body = String.Format(mailTemplate,
                    user.Firstname,
                    user.Lastname,
                    GetAppServer(),
                    user.ActivationCode);
            email.IsBodyHtml = true;
            MailSender.Instance.SendMailAsync(email);
        }

        private void SetNotificationAdmins(Musicman.Common.Entities.User user)
        {
            List<Musicman.Common.Entities.User> admins = UserManager.Instance.LoadAdminUsers();
            if (admins.Count == 0)
            {
                return;
            }
            MailMessage email = new MailMessage();
            string mailTemplate = "";
            using (StreamReader sr = new StreamReader(File.Open(Server.MapPath("templates//new_user_mail.html"), FileMode.Open, FileAccess.Read)))
            {
                mailTemplate = sr.ReadToEnd();
            }
            email.From = new MailAddress("musicmanservices@musicman.com", "Musicman");
            for (int i = 0; i < admins.Count; i++)
            {
                email.To.Add(new MailAddress(admins[i].Emailaddress));
            }
            email.Subject = "New Musicman account created";
            email.Body = String.Format(mailTemplate,
                    user.Firstname,
                    user.Lastname,
                    user.Emailaddress);
            email.IsBodyHtml = true;
            MailSender.Instance.SendMailAsync(email);
        }
    }
}
